package com.vids.controller;

import cn.hutool.core.text.CharSequenceUtil;
import com.vids.constant.VIIDRespEnum;
import com.vids.model.entity.User;
import com.vids.model.response.ResponseStatus;
import com.vids.service.IUserService;
import com.vids.utils.BeanUtilss;
import com.vids.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 系统用户表 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/VIID")
public class UserController
{
    @Autowired
    private IUserService userService;

    /**
     * @param user
     * @return
     * @throws Exception
     */
    @PostMapping("/User")
    public Object createUser(@RequestBody User user) throws Exception
	{
        ResponseStatus status = new ResponseStatus("/User", VIIDRespEnum.OK.getCode(), new Date());
        if (user == null) {
            setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数为空");
        } else if (CharSequenceUtil.isBlank(user.getLogonName())) {
            setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "账号LogonName为空");
        } else if (CharSequenceUtil.isBlank(user.getPassword())) {
            setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "登陆密码Password为空");
        } else {
            userService.save(user);
            status.setStatusString("保存成功");
        }
        return new ResponseEntity<>(BeanUtilss.objectToMap(BeanUtilss.getResponseModel(status)),
                HttpStatus.CREATED);
    }

    @GetMapping(value = "/User/{logName}", produces = "application/VIID+JSON;charset=UTF-8")
    public Object getUserInfo(@PathVariable("logName") String logName)
	{
        User user = userService.findByLogName(logName);
        if (user == null) {
            return new ResponseEntity<Map<String, Object>>(new HashMap<String, Object>(), HttpStatus.NO_CONTENT);
        }
        return user;
    }

    protected void setStatus(ResponseStatus res, VIIDRespEnum e, String field)
	{
        StringBuffer sb = new StringBuffer();
        sb.append(e.getMsg() + "[" + field + "]");
        res.setStatusCode(e.getCode());
        res.setStatusString(sb.toString());
    }
}
